package com.domain.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.domain.model.Sysrole;
import com.domain.model.Sysuser;
import com.domain.service.RoleService;
import com.domain.service.UserService;
import com.domain.util.commonUtil;

@Controller
@RequestMapping("/user")
public class UserController extends SuperController {
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	
	@RequestMapping("/top.html")
	public String toTop(HttpServletRequest request,ModelMap model){
		Sysuser user=(Sysuser) request.getSession().getAttribute(commonUtil.CURRENTUSER);
		model.addAttribute("user", user);
		return "frame/Top";
	}
	
	@RequestMapping("/index.html")
	public String index(HttpServletRequest request){
		return "frame/main";
	}
	@RequestMapping("/toAddUser/{porCode}.html")
	public String toAddUser(HttpServletRequest request,@PathVariable String porCode,ModelMap model){
		List<Sysrole> roles = roleService.doRoleList();
		request.setAttribute("roles", roles);
		model.put(POR_CODE, porCode);
		return "system/addUser";
	}
	
	@RequestMapping("/addUser/{porCode}.html")
	public String doAddUser(Sysuser user,@PathVariable String porCode,ModelMap model){
		userService.doAdd(user);
		return "redirect:/user/toList.html";
	}
	
	/**
	 * 查询角色列表
	 */
	@RequestMapping("/toList.html")
	public String toUserList(HttpServletRequest request,String porCode,ModelMap model){
		List<Sysuser> users = userService.doUserList();
		request.setAttribute("users", users);
		model.put(POR_CODE, porCode);
		return "system/userList";
	}
	
	
	/**
	 * 进入用户编辑页面
	 */
	@RequestMapping("/toEditUser/{porCode}.html")
	public String toEditUser(HttpServletRequest request,Long id,@PathVariable String porCode,ModelMap model){
		Sysuser user = userService.getUserById(id);
		request.setAttribute("user", user);
		List<Sysrole> roles = roleService.doRoleList();
		request.setAttribute("roles", roles);
		model.put(POR_CODE, porCode);
		return "system/editUser";
	}

	/**
	 * 编辑用户信息角色
	 */
	@RequestMapping("/editUser/{porCode}.html")
	public String doEditUser(Sysuser user,@PathVariable String porCode,ModelMap model){
		try {
			userService.editUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put(POR_CODE, porCode);
		return "redirect:/user/toList.html";
	}
	
	/**
	 * 编辑角色信息角色
	 */
	@RequestMapping("/doDelUser/{porCode}.html")
	public String doDelUser(Long id,@PathVariable String porCode,ModelMap model){
		//userService.doAdd(user);
		try {
			
			userService.doDelUser(id);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		model.put(POR_CODE, porCode);
		return "redirect:/user/toList.html";
	}
	
	
}
